<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <link rel="stylesheet" href="../css/jsdeliverbootstrap.min.css">
<!--  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css"-->
<!--        integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">-->
  <link rel="stylesheet" href="../css/pet-store-plus.css">

  <link rel="stylesheet" href="/css/staticfilebootstrap.min.css">
<!--  <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">-->

  <script src="/js/chart.js"></script>
<!--  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>-->

  <title>Product管理</title>

</head>
<body>

<div th:replace="seller_commom"></div>

<div class="content" id="content">
  <div style="grid-column: span 3"></div>
  <div class="searchgrp" >
    <form >
      <input type="text" placeholder="可通过商品名搜索..." class="searchinput" id="keyword" name="keyword">
      <button class="searchbtn" onclick="searchProduct()" type="button"  >搜索</button>
      <!--            ///admin/getItemListByKeyForJS-->
    </form>
  </div>
  <button class="Button" style="margin-top: 10px;width: 150px" onclick="window.location.href='/admin/add'"  id="add">
    添加商品
  </button>
  <div class="tab-bg">
    <table class="item_tab"  id="item_tab" style="overflow: auto">
      <caption></caption>
      <thead>
      <tr>
        <th>Id</th>
        <th>产品名称</th>
        <th>Category</th>
        <th>图像</th>
        <th>描述</th>
        <th>操作</th>
      </tr>
      </thead>
      <tbody id="proTabBody">
      </tbody>
    </table>

  </div>
</div>

<script th:inline="javascript">
  const tbody=document.getElementById('proTabBody');
  window.addEventListener('load',function (){
    console.log('aaa');
    var url='/admin/showProduct';
    fetch(url,{
      method:'GET',
    }).then(response=>{
      if(!response.ok){
        console.log("请求/admin/showProduct失败 ，状态码：" + response.status);
      }else {
        return response.json();
      }
    }).then(data=>{
     console.log('show product');
     console.log(data.data);
     updateTbody(data.data);
    })
  })

  function searchProduct(){
    var keyword=document.getElementById('keyword').value;
    console.log(keyword);
    var url='/admin/getProductListByKeyForJS?keyword='+keyword;
    fetch(url)
            .then(response => {
              if (!response.ok) {
                throw new Error('Network response was not ok.');
              }
              return response.json(); // 解析JSON格式的响应数据
            })
            .then(data => {
              // 处理返回的数据
              console.log(data);
              tbody.innerHTML = '';
              var newProducts = data.data;
              updateTbody(newProducts);
            })
            .catch(error => {
              console.error('请求发生错误', error);
            });

  }

  function updateTbody(newProducts){
    // let isupText='';
    // let buttonText='';
    console.log('update');
    tbody.innerHTML='';
    newProducts.forEach(function(product) {

      var newRow = document.createElement('tr');
      newRow.innerHTML=`
<!--<form action="/productEditor" method="post" enctype="multipart/form-data">-->
                <td name="productid" >${product.productid}</td>
                <td name="productname" >${product.name}</td>
                <td name="categoryid" >${product.category}</td>


             <td><div class="image-upload-container1">
            <input type="file" id="imageInput1" accept="image/*" name="pic" onchange="previewImage1(event)" readonly>
            <label for="pic" style="top: 50%; left: 50%; transform: translate(-50%, -50%);"></label>
            <img id="imagePreview1" class="image-preview round-image" src="${product.descn}" alt="Image Preview" >
            </div></td>

                <td name="attr"><textarea name="attr" class="proAttr" readonly></textarea></textarea>
                </td>
                <td>
                    <button class="edit Button" style="display: inline-block;" onclick="editProduct(this)" id="editProduct">编辑</button>
                    <button class="save Button" style="display: none;" onclick="saveProduct(this)" id="saveProduct" type="submit">保存</button>
                     <button class="sell-btn Button" style="display: inline-block;" onclick="deleteProduct(this)">删除</button>
                </td>
<!--                </form>-->
                    `;
      var proAttr=newRow.querySelector('.proAttr');
      console.log('.proAttr'+proAttr);
      proAttr.value=product.textdescn;
      tbody.appendChild(newRow);
      var preview = newRow.querySelector('.image-preview')
      console.log('preview='+preview);
          // preview.src = product.descn;
      preview.src = decodeURI(product.descn);
          console.log(preview.src);
          preview.style.display = 'block';

    })
  }
function deleteProduct(button){
        var row=button.parentNode.parentNode;
      var productid=row.querySelector('td:nth-child(1)').innerText;

      var result = confirm("Are you sure you want to delete the product "+productid+"?");
  const url = `/admin/deleteProductById?productId=${productid}`;
      if (result) {
        fetch(url, {
          method: 'GET' // 使用 GET 方法
        })
                .then(response => response.json())
                .then(data => {
                  if(data.message!=null){
                    alert('删除失败:'+data.message);
                  } else {
                      alert('删除成功');
                      row.remove();
                  }
                })
                .catch(error => {
                  console.error('Error:', error);
                });
      }
}


    function saveProduct(button) {
      var row = button.parentNode.parentNode;
      var des = row.querySelector('.proAttr').value;
      var imagePreview = row.querySelector('img');
      var fileInput = row.querySelector('input[type=file]')
      var file = fileInput.files[0];
      var formData = new FormData();
      var productid = row.querySelector('td:nth-child(1)').innerText;
      formData.append('textdescn', des); // 添加文本描述到 FormData 对象
      formData.append('productId', productid); // 添加产品ID到 FormData 对象

      // 检查是否有新的文件被选择，如果没有则使用之前已经上传的文件
      if (file) {
        formData.append('pic', file);
        sendSaveReq(button,formData)
      } else {
        // 如果没有新的文件被选择，则使用之前已经上传的文件
        // 获取图片元素
        var imagePreview = row.querySelector('img');

// 将图片转换为文件对象
        var imageUrl = imagePreview.src;
        var imageName = imageUrl.split('/').pop(); // 获取图片名
        console.log('imageUrl=' + imageUrl);
        console.log('imageName=' + imageName);
        imagetoFile(imagePreview,imageName,formData,button);

      }
    }

  function sendSaveReq(button,formData){
    var row = button.parentNode.parentNode;
    var editButton = row.querySelector('#editProduct');
    var textareaFields = row.querySelectorAll('textarea');
    fetch('/productEditor', {
      method: 'POST',
      body: formData
    })
            .then(response => {
              if (response.ok) {
                console.log("保存成功");
                console.log("编辑按钮：" + editButton)
                editButton.style.display = 'inline-block';
                button.style.display = 'none';
                textareaFields.forEach(function (input) {
                  input.setAttribute("readonly", "true");
                  input.style.border = "none";
                });
              } else {
                console.log("保存失败");
                alert('商品保存失败');
              }
              response.json()
            }) // 解析响应为 JSON 格式

            .catch(error => {
              // 处理错误
              console.error('Error:', error);
            });

  }


  function imagetoFile(image, imageName, formData, button){
    var file
    var cvs = document.createElement("canvas");
    var ctx = cvs.getContext('2d');
    cvs.width = image.width;
    cvs.height = image.height;
    ctx.drawImage(image, 0, 0, cvs.width, cvs.height);
    console.log('cvs='+cvs);
    cvs.toBlob(function(blob) {
      // 在此处处理生成的 Blob 对象
      console.log('blob='+blob);
      file = new File([blob], imageName, { type: blob.type });
      formData.append('pic', file);
      console.log('file2='+file);
      if (typeof file === 'object' && file instanceof File) {
        console.log('文件已生成');
      } else {
        console.log('文件未生成');
      }

      for (var pair of formData.entries()) {
        console.log(pair[0] + ', ' + pair[1]);
      }
      sendSaveReq(button,formData);


    }, 'image/png');

  };

    function editProduct(button) {
      var row = button.parentNode.parentNode;
      var textFields = row.querySelectorAll('textarea');
      var saveButton = row.querySelector('#saveProduct');
      textFields.forEach(function (input) {
        input.removeAttribute("readonly");
        input.style.border = "1px solid #ccc"; // 可以添加边框样式来提示用户
      });
      button.style.display = "none"; // 隐藏当前行的编辑按钮
      saveButton.style.display = 'inline-block';

    }

    function previewImage1(event) {
      console.log('选择图片');
      var input = event.target;
      var row = input.parentNode.parentNode;
      // var preview = row.getElementById('imagePreview1');
      var preview = row.querySelector('img')
      if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
          preview.src = e.target.result
          preview.style.display = 'block'; // 在if语句块中显示预览图片
        }
        reader.readAsDataURL(input.files[0]);
      }
    }



</script>

</body>
</html>